import cv2 as cv
# 加载图片
imgL = cv.imread('LENA.jpg')
imgR = cv.imread('LENA.jpg')
# 转换为灰度图
grayL = cv.cvtColor(imgL, cv.COLOR_BGR2GRAY)

grayR = cv.cvtColor(imgR, cv.COLOR_BGR2GRAY)
# 提取特征点
sift = cv.xfeatures2d_SIFT.create()
kL, dL = sift.detectAndCompute(grayL, None)
kR, dR = sift.detectAndCompute(grayR, None)

# 创建 BFMatcher 对象
bf = cv.BFMatcher(cv.NORM_L2)
# 根据描述子匹配特征点.
matches = bf.match(dL, dR)
# 画出匹配点
img3 = cv.drawMatches(imgL, kL, imgR, kR, matches, None, flags=2)
cv.imshow("SIFT", img3)
# ------------------------------------------------------------------------------------------------
# 设置FLANN 超参数
FLANN_INDEX_KDTREE = 0
# K-D树索引超参数
index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)
# 搜索超参数
search_params = dict(checks=50)
# 初始化FlannBasedMatcher匹配器
flann = cv.FlannBasedMatcher(index_params, search_params)
# 通过KNN的方式匹配两张图的描述子
matches = flann.knnMatch(dL, dR, k=2)
# 筛选比较好的匹配点
good = []
for i, (m, n) in enumerate(matches):
    if m.distance < 0.6 * n.distance:
        good.append(m)
# 画出匹配点
img3 = cv.drawMatches(imgL, kL, imgR, kR, good, None, flags=2)
cv.imshow("SIFT-FLANN", img3)
cv.waitKey(0)
